import Cesium, { Cartesian2, GeometryInstance, Primitive } from "../Ces/Cesium"


class WeWindStreamlineVolumePrimitive {
  private primitive: Primitive
  constructor(
    { features, scaleZ, circleStep, circleRadius,
      extrusionHeight }
  ) {
    function computeCircle(radius) {
      const positions: Cartesian2[] = []
      for (let i = 0; i < circleStep; i++) {
        const radians = Cesium.Math.toRadians(i * (360 / circleStep))
        positions.push(
          new Cesium.Cartesian2(radius * Math.cos(radians), radius * Math.sin(radians)),
        )
      }
      return positions
    }

    const geometryInstances: GeometryInstance[] = []

    for (const f of features) {
      const polylinePositions: any[] = []
      for (let i = 0; i < f.geometry.coordinates.length; i += 3) {
        const lon = f.geometry.coordinates[i]
        const lat = f.geometry.coordinates[i + 1]
        const height = f.geometry.coordinates[i + 2]
        polylinePositions.push(Cesium.Cartesian3.fromDegrees(lon, lat, extrusionHeight * height * scaleZ))
      }
      const geometry = new Cesium.PolylineVolumeGeometry({
        vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
        polylinePositions,
        shapePositions: computeCircle(circleRadius),
      })
      geometryInstances.push(
        new Cesium.GeometryInstance({
          geometry,
          attributes: {
            color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.DARKCYAN),
          },
        }),
      )
    }
    const primitive = new Cesium.Primitive({
      geometryInstances,
      appearance: new Cesium.PerInstanceColorAppearance({
        flat: false,
        translucent: false,
      }),
      asynchronous: true,
    })


    this.primitive = primitive
  }

  update(frameState) {
    //@ts-ignore
    this.primitive?.update(frameState)
  }

  isDestroyed() { return false }

  destroy() {
    //@ts-ignore
    this.primitive = this.primitive && this.primitive.destroy()
    return Cesium.destroyObject(this)
  }
}

export default WeWindStreamlineVolumePrimitive
